import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSystemTrayIcon,QMenu,QAction,QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5 import QtGui
class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.initUI()

    def initUI(self):
        # 窗口属性
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('My Window')

        # 托盘图标
        tray_icon = QSystemTrayIcon(QIcon('D:/huohua_002.png'), self)
        tray_icon.setToolTip('My Application')
        tray_icon.activated.connect(self.iconActivated)
        tray_icon.show()
        # 托盘创建出来时显示的信息
        tray_icon.showMessage(u"标题", '托盘信息内容', icon=1)  # icon的值  0没有图标  1是提示  2是警告  3是错误

        # 右键菜单
        menu = QMenu()
        exit_action = QAction('退出(&Q)', self)
        exit_action.triggered.connect(QApplication.instance().quit)
        menu.addAction(exit_action)
        tray_icon.setContextMenu(menu)

    def iconActivated(self, reason):
        print(reason)
        print(QSystemTrayIcon.DoubleClick,"---------------")
        if reason == QSystemTrayIcon.DoubleClick:  # 双击 显示或隐藏窗口
            self.a()
        elif reason == QSystemTrayIcon.Trigger:  # 单击  #MiddleClick  中键双击
            pass

    # 响应托盘双击，最大最小化界面
    def a(self):
        if self.isMinimized() or not self.isVisible():
            # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
            self.showNormal()
            self.activateWindow()
        else:
            # 若不是最小化，则最小化
            self.showMinimized()

    # 窗口关闭事件
    def closeEvent(self, event):
        event.ignore()
        self.hide()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())